package style.JUC多线程与并发.DeadLock;

import java.util.concurrent.TimeUnit;

class MyTask implements Runnable{

    private Object resourceA, resourceB;

    public MyTask(Object resourceA, Object resourceB){
        this.resourceA = resourceA;
        this.resourceB = resourceB;
    }


    @Override
    public void run() {
        synchronized (resourceA){
            System.out.println(String.format("%s 自己持有%s, 尝试获取 %s",
                    Thread.currentThread().getName(),
                    resourceA, resourceB));
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (resourceB){
                System.out.println(String.format("%s 自己持有%s， 尝试获取 %s",
                        Thread.currentThread().getName(),
                        resourceB,
                        resourceA));
            }

        }
    }
}

public class DeadLockDemo {
    public static void main(String[] args) {
        Object A = new Object();
        Object B = new Object();

        new Thread(new MyTask(A, B),"ThreadA").start();
        new Thread(new MyTask(B, A),"ThreadB").start();
    }
}
